
<template>
    <div class="execution">
        <basic-container>
            <avue-crud
              v-model="form"
              v-bind="bindVal"
              v-on="onEvent"
              :page.sync="page"
              @selection-change="selectionChange"
              :permission="permissionList">
              <template slot="menuLeft">
                <el-button type="primary" size="small" @click="handleCreate">申请权限变更</el-button>
                <el-upload
                  class="upload-inline"
                  action=""
                  :show-file-list="false"
                  accept=".xls,.xlsx"
                  :http-request="handleImport">
                  <el-button type="primary" size="small">批量导入</el-button>
                </el-upload>
                <el-button v-if="permissions.sys_role_change_approve" type="primary" size="small" @click="handleBatchApprove">批量审批</el-button>
                <el-button v-if="permissions.sys_role_change_submit"
                           type="primary"
                           size="small"
                           @click.stop="handleBatchSubmit()">提交</el-button>
              </template>
              <template slot-scope="scope" slot="menu">
                <el-button v-if="scope.row.status == 1"
                           type="text"
                           icon="el-icon-edit"
                           size="small"
                           @click.stop="handleEdit(scope.row,scope.index)">编辑</el-button>
                <el-button v-if="permissions.sys_role_change_approve && scope.row.status == 2"
                           type="text"
                           icon="el-icon-tickets"
                           size="small"
                           @click.stop="handleApprove(scope.row,scope.index)">审批</el-button>
                <el-button v-if="(scope.row.status == 1)"
                           type="text"
                           icon="el-icon-delete"
                           size="small"
                           @click.stop="rowDel(scope.row,scope.index)">删除</el-button>
              </template>
              <template slot-scope="scope" slot="userCodeForm">
                <avue-input
                  v-model="form.userCode"
                  placeholder="请输入用户号"/>
              </template>
              <template slot-scope="scope" slot="newRoleForm">
                <avue-select
                  v-model="form.newRole"
                  :dic="rolesOptions"
                  :props="roleProps"
                  placeholder="请选择现有角色"/>
              </template>
              <template slot-scope="scope" slot="oldRoleForm">
                <avue-select
                  v-model="form.oldRole"
                  :dic="rolesOptions"
                  :props="roleProps"
                  disabled/>
              </template>
            </avue-crud>
        </basic-container>
      <el-dialog
        :visible.sync="dialogApproveVisible"
        :close-on-click-modal="false"
        title="审批权限变更">
        <avue-form ref="form" v-model="approveData" :option="approveOption" @submit="submitRoleChange">
        </avue-form>
      </el-dialog>
    </div>
</template>

<script>
    import {fetchList, getObj, addObj, putObj, delObj, saveBatch, submitRoleChange, approveRoleChange} from '@/api/admin/role-change'
    import {fetchList as fetchUserList} from '@/api/admin/user'
    import {deptRoleList} from '@/api/admin/role'
    import {tableOption} from '@/const/crud/admin/role-change'
    import {mapGetters} from 'vuex'
    import baseCrud from '@/mixins/base-crud'
    export default {
        name: 'sysrolechange',
        mixins: [baseCrud('admin/role-change')],
        data() {
          var that = this
          const validatorRemark = (rule, value, callback) => {
            if (this.approveData.status === 4 && !value) {
              callback(new Error("请填写备注信息"))
            } else {
              callback()
            }
          }
          const validateUserCode = (rule, value, callback) => {
            fetchUserList({userCode: value}).then(response => {
              if(response.data.data.records.length > 0){
                const user = response.data.data.records[0]
                that.form.userId = user.userId
                that.form.userName = user.nikename
                that.form.lineName = user.lineCode
                that.form.station = user.stationCode
                that.form.oldRole = user.roleList[0].roleName
                callback()
              }else{
                callback(new Error("用户号不存在"))
              }
            })
          }
          tableOption.column[1].rules = [{
            required: true,
            message: '请输入员工号'
          },{
            validator: validateUserCode, trigger: 'blur'
          }]
          return {
                searchForm: {},
                tableData: [],
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                tableLoading: false,
                tableOption: tableOption,
                dialogApproveVisible: false,
                selectedRows: [],
                approveData: {
                  idList: [],
                  status: 3,
                  checkerRemark: ""
                },
                approveOption: {
                  emptyBtn: false,
                  column: [{
                    label: "审批意见",
                    prop: "status",
                    type: "radio",
                    dicData:  [{
                      label: '同意',
                      value: 3
                    }, {
                      label: '不同意',
                      value: 4
                    }],
                    span: 24
                  },{
                    label: "备注",
                    prop: "checkerRemark",
                    type: "textarea",
                    placeholder: "不同意写出原因",
                    rules: [
                      { validator: validatorRemark, trigger: 'blur'}
                    ],
                    span: 24
                  }]
                },
                rolesOptions: [],
                roleProps: {
                  label: 'roleName',
                  value: 'roleName'
                },
                form: {}
            }
        },
        computed: {
            ...mapGetters(['permissions']),
            permissionList() {
                return {
                    addBtn: this.vaildData(this.permissions.generator_sysrolechange_add, false),
                    delBtn: this.vaildData(this.permissions.generator_sysrolechange_del, false),
                    editBtn: this.vaildData(this.permissions.generator_sysrolechange_edit, false)
                };
            }
        },
        created() {
          this.sys_user_add = this.permissions['sys_user_add']
          this.sys_user_edit = this.permissions['sys_user_edit']
          this.sys_user_del = this.permissions['sys_user_del']
        },
        methods: {
            getList(page, params) {
                this.tableLoading = true
                return fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize
                }, params, this.searchForm )).then(response => {
                    this.tableData = response.data.data.records
                    this.page.total = response.data.data.total
                    this.tableLoading = false
                }).catch(() => {
                    this.tableLoading=false
                })
            },
            rowDel: function (row, index) {
                var _this = this
                this.$confirm('您是否要删除此数据?', '提示', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'warning'
                }).then(function () {
                    return delObj(row.id)
                }).then(data => {
                    _this.$message.success('删除成功')
                    this.getList(this.page)
                })
            },
            handleUpdate: function (row, index, done,loading) {
                putObj(row).then(data => {
                    this.$message.success('修改成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            handleSave: function (row, done,loading) {
                let obj = {
                  userId: row.userId,
                  lineName: row.lineName,
                  station: row.station,
                  newRole: row.newRole,
                  oldRole: row.oldRole,
                  remark: row.remark
                }
                addObj(obj).then(data => {
                    this.$message.success('申请成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            handleCreate() {
              this.getRoleList()
              this.$refs.crud.rowAdd()
            },
            getRoleList(){
              deptRoleList().then(response => {
                this.rolesOptions = response.data.data;
                //const roles =  this.rolesOptions.filter(w => w.roleCode== 'CZZZ' || w.roleCode=='ZZZL' || w.roleCode=='ZBZZ' || w.roleCode=='KZRY' || w.roleCode=='KYZBY' || w.roleCode=='ZHANWURENYUAN');
                const roles = this.rolesOptions.filter(
                  w =>
                    w.roleCode == "KYZBY" ||
                    w.roleCode == "ZBZZ" ||
                    w.roleCode == "ZHANWURENYUAN" ||
                    w.roleCode == "CZZZ"
                );
                this.rolesOptions = roles;
              })
            },
            handleImport(item){
              let file = item.file
              let param = new FormData()
              param.append('file',file)
              saveBatch(param).then(() => {
                this.$notify({
                  title: '成功',
                  message: '导入成功',
                  type: 'success',
                  duration: 2000
                })
                this.getList(this.page)
              })
            },
            handleEdit(row, index) {
              this.$refs.crud.rowEdit(row, index)
            },
            // handleSubmit(row, index){
            //   submitRoleChange(row.id).then(response => {
            //     this.$notify({
            //       title: '成功',
            //       message: '提交成功',
            //       type: 'success',
            //       duration: 2000
            //     })
            //     this.getList(this.page)
            //   })
            // },
            handleApprove(row, index) {
              this.approveData.idList = [row.id]
              this.dialogApproveVisible = true
            },
            submitRoleChange(form,done){
                approveRoleChange(this.approveData).then(data => {
                this.$notify({
                  title: '成功',
                  message: '审批成功',
                  type: 'success',
                  duration: 2000
                })
                done()
                this.dialogApproveVisible = false
                this.getList(this.page)
              }).catch(() => {
                done()
              });
            },
            selectionChange(list){
                this.selectedRows = list
            },
            handleBatchApprove(){
                if(this.selectedRows.length > 0 ){
                    this.approveData.idList = []
                    for(let row of this.selectedRows){
                      if(row.status === 2){
                        this.approveData.idList.push(row.id)
                      }else {
                        this.$message.info("请选择已提交的记录")
                        return
                      }
                    }
                    this.dialogApproveVisible = true
                }else{
                    this.$message.info("请选择要审批的记录")
                }
            },
            searchChange(form, done) {
                this.searchForm = form
                this.getList(this.page, form).then(() => {
                  done()
                })
            },
            refreshChange() {
                this.getList(this.page)
            }
        }
    }
</script>

<style lang="scss">
  .upload-inline {
    display: inline-block;
  }
</style>
